// AdminLayout.tsx
import React, { useState, useEffect } from 'react';
import { Outlet, useNavigate, useLocation } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import {
  HomeOutlined,
  DashboardOutlined,
  TeamOutlined,
  ShopOutlined,
  UsergroupAddOutlined,
  BankOutlined,
  CalendarOutlined,
  VideoCameraOutlined,
  UserOutlined,
  FileTextOutlined,
  SettingOutlined,
  UserSwitchOutlined
} from '@ant-design/icons';
import LanguageButton from '../../components/LanguageButton';
import SimpleFloatingBall from '../../components/SimpleFloatingBall';
import styles from './AdminLayout.module.css';

interface User {
  id: number;
  username: string;
  email: string;
  role: string;
}

const AdminLayout: React.FC = () => {
  const { t } = useTranslation(['common', 'layout']);
  const navigate = useNavigate();
  const location = useLocation();
  const [expandedMenus, setExpandedMenus] = useState<Set<string>>(new Set(['students']));
  const [userPermissions, setUserPermissions] = useState<string[]>([]);
  const [permissionsLoaded, setPermissionsLoaded] = useState(false);

  const getUserInfo = (): User | null => {
    try {
      const userStr = localStorage.getItem('user');
      return userStr ? JSON.parse(userStr) : null;
    } catch (error) {
      console.error(t('common:getUserInfoError'), error);
      return null;
    }
  };

  const currentUser = getUserInfo();
  const username = currentUser?.username || t('common:user');
  const userRole = currentUser?.role || '';

  // 加载用户权限
  useEffect(() => {
    const loadUserPermissions = async () => {
      try {
        const token = localStorage.getItem('accessToken') || localStorage.getItem('token');
        if (!token) {
          setPermissionsLoaded(true);
          return;
        }

        const response = await fetch('http://localhost:3001/api/permissions/me', {
          headers: {
            'Authorization': `Bearer ${token}`
          }
        });

        if (response.ok) {
          const result = await response.json();
          const permissionCodes = result.data?.permissionCodes || [];
          setUserPermissions(permissionCodes);
          console.log('当前用户权限:', permissionCodes);
        } else {
          console.error('获取用户权限失败:', response.status);
        }
      } catch (error) {
        console.error('加载用户权限失败:', error);
      } finally {
        setPermissionsLoaded(true);
      }
    };

    loadUserPermissions();
  }, []);

  // 检查用户是否有指定权限
  const hasPermission = (permissionCode: string): boolean => {
    if (userRole === 'admin') return true;
    return userPermissions.includes(permissionCode);
  };

  const handleLogout = () => {
    if (window.confirm(t('common:confirmLogout'))) {
      localStorage.removeItem('token');
      localStorage.removeItem('accessToken');
      localStorage.removeItem('user');
      window.location.href = '/login';
    }
  };

  const menuItems = [
    { id: 'home', path: '/admin/home', labelKey: 'menu.home', icon: HomeOutlined },
    { id: 'dashboard', path: '/admin/dashboard', labelKey: 'menu.dashboard', icon: DashboardOutlined },
    { 
      id: 'students', 
      path: '/admin/students', 
      labelKey: 'menu.studentManagement',
      icon: TeamOutlined,
      children: [
        { id: 'students-main', path: '/admin/students', labelKey: 'menu.studentManagement', icon: TeamOutlined },
        { id: 'marketing', path: '/admin/students/marketing', labelKey: 'menu.marketingManagement', icon: ShopOutlined },
        { id: 'classes', path: '/admin/students/classes', labelKey: 'menu.classManagement', icon: UsergroupAddOutlined },
        { id: 'colleges', path: '/admin/students/colleges', labelKey: 'menu.collegeManagement', icon: BankOutlined },
        { id: 'dormitories', path: '/admin/students/dormitories', labelKey: 'menu.dormitoryManagement', icon: HomeOutlined },
        { id:'kaoqing',path:'/admin/students/kaoqing',labelKey:'menu.attendanceManagement', icon: CalendarOutlined }
      ]
    },

    { id: 'video-conference', path: '/admin/video-conference', labelKey: 'menu.videoConference', icon: VideoCameraOutlined },
    { id: 'teachers', path: '/admin/teachers', labelKey: 'menu.teacherManagement', icon: UserOutlined },
    { id: 'grades', path: '/admin/grades', labelKey: 'menu.gradeManagement', icon: FileTextOutlined },
    { id: 'profile', path: '/admin/profile', labelKey: 'menu.userCenter', icon: UserSwitchOutlined },
    { id: 'settings', path: '/admin/settings', labelKey: 'menu.systemSettings', icon: SettingOutlined }
  ];

  // 根据用户权限过滤菜单项（等待权限加载完成）
  const menuItems = permissionsLoaded ? allMenuItems
    .filter(item => {
      // 如果没有要求的权限，所有人都可以访问
      if (!item.requiredPermission) return true;

      // 检查用户是否有该权限
      return hasPermission(item.requiredPermission);
    })
    .map(item => {
      // 如果有子菜单，也过滤子菜单
      if (item.children) {
        return {
          ...item,
          children: item.children.filter(child => {
            if (!child.requiredPermission) return true;
            return hasPermission(child.requiredPermission);
          })
        };
      }
      return item;
    })
    .filter(item => {
      // 如果是有子菜单的项，至少保留一个子菜单才显示父菜单
      if (item.children && item.children.length === 0) {
        return false;
      }
      return true;
    }) : []; // 权限未加载完成时，不显示任何菜单（避免闪烁）

  const toggleMenu = (menuId: string) => {
    setExpandedMenus(prev => {
      const newSet = new Set(prev);
      if (newSet.has(menuId)) {
        newSet.delete(menuId);
      } else {
        newSet.add(menuId);
      }
      return newSet;
    });
  };

  const isStudentsActive = location.pathname.startsWith('/admin/students');

  return (
    <div className={styles.adminLayout}>
      {/* 侧边栏 */}
      <div className={styles.sidebar}>
        <div className={styles.sidebarHeader}>
          <h2>{t('layout:adminSystemTitle')}</h2>
        </div>
        <nav className={styles.sidebarNav}>
          {menuItems.map(item => (
            <div key={item.id} className={styles.menuItem}>
              {item.children ? (
                <>
                  <button
                    className={`${styles.hasChildren} ${isStudentsActive ? styles.active : ''
                      }`}
                    onClick={() => toggleMenu(item.id)}
                  >
                    {item.icon && React.createElement(item.icon, { className: styles.menuIcon })}
                    <span className={styles.navItemText}>{t(`layout:${item.labelKey}`)}</span>
                    <span className={`${styles.navItemArrow} ${expandedMenus.has(item.id) ? styles.expanded : ''}`}>
                      {expandedMenus.has(item.id) ? '▼' : '▶'}
                    </span>
                  </button>

                  {item.children && (
                    <div className={`${styles.submenu} ${expandedMenus.has(item.id) ? styles.expanded : ''}`}>
                      {item.children.map(child => (
                        <button
                          key={child.id}
                          className={`${styles.submenuItem} ${location.pathname === child.path ? styles.active : ''}`}
                          onClick={() => navigate(child.path)}
                        >
                          {child.icon && React.createElement(child.icon, { className: styles.submenuIcon })}
                          {t(`layout:${child.labelKey}`)}
                        </button>
                      ))}
                    </div>
                  )}
                </>
              ) : (
                <button
                  className={`${styles.navItem} ${location.pathname === item.path ? styles.active : ''}`}
                  onClick={() => navigate(item.path)}
                >
                  {item.icon && React.createElement(item.icon, { className: styles.menuIcon })}
                  <span className={styles.navItemText}>
                    {item.labelKey ? t(`layout:${item.labelKey}`) : ''}
                  </span>
                </button>
              )}
            </div>
          ))}
        </nav>
      </div>

      {/* 主内容区域 */}
      <div className={styles.mainContent}>
        {/* 顶部导航栏 */}
        <div className={styles.contentHeader}>
          <div className={styles.headerLeft}>
            {/* 标题显示区域，现在为空 */}
          </div>
          <div className={styles.headerRight}>
            <div className={styles.userInfo}>
              <LanguageButton />
              <span className={styles.welcomeText}>{t('common:welcome')}，</span>
              <span className={styles.username}>{username}</span>
              <button onClick={handleLogout} className={styles.logoutBtnHeader}>
                {t('common:logout')}
              </button>
            </div>
          </div>
        </div>

        {/* 页面内容区域 */}
        <div className={styles.contentBody}>
          <Outlet />
        </div>
      </div>

      {/* AI悬浮球 */}
      <SimpleFloatingBall />
    </div>
  );
};

export default AdminLayout;